<template>
  <a-spin :spinning="confirmLoading" style="background: #fff">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">
          <a-collapse-panel key="1" header="基础信息">
            <a-row :gutter="48">
              <a-col :span="8" :hidden="true">
                <a-form-model-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle">
                  <a-input
                    :disabled="formDisabled"
                    v-model="model.bpmBizTitle"
                    placeholder="请输入标题"
                    :max-length="255"
                  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billNo">
                  <a-input v-model="model.billNo" placeholder="请输入单据编号" disabled></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="填报日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
                  <j-date
                    placeholder="请选择创建日期"
                    v-model="model.createTime"
                    :show-time="true"
                    date-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                    disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposer">
                  <select-user-by-dep
                    :multi="false"
                    v-model="model.proposer"
                    disabled></select-user-by-dep>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposerDeptId">
                  <j-select-depart v-model="model.proposerDeptId" disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="费用所属团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamId">
                  <select-team-input
                     :proposerDeptId="model.proposerDeptId"
                     isApi="expenseReimbursement"
                    :disabled="formDisabled || showFlowSubmitButton"
                    v-model="model.teamId"
                    :tdlx="3"
                    @back="selectTeam"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请公司" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applicant">
                  <select-Company-input :disabled="formDisabled || showFlowSubmitButton" v-model="model.applicant" @change="selectApplicant"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="单据类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billCategory">
                  <j-dict-select-tag :disabled="formDisabled || showFlowSubmitButton" type="list" v-model="model.billCategory" dictCode="bill_category" placeholder="请选择单据类型" />
                </a-form-model-item>
              </a-col>

              <a-col :span="8" v-if="model.teamYear=='2023'">
                <a-form-model-item label="费用所属年度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamYear">
                  <j-dict-select-tag
                    type="list"
                    v-model="model.teamYear"
                    dictCode="tdnd_type"
                    placeholder="请选择费用所属年度"
                    disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8" >
                <a-form-model-item label="本次支付（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="payAmount">
                  <a-input-number
                    disabled
                    :max="99999999"
                    :min="0"
                    v-model="model.payAmount"
                    placeholder="请输入本次支付"
                    style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="16">
                <a-form-model-item label="申请公司" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applicant">
                  <j-select-depart :disabled="formDisabled" v-model="model.applicant" placeholder="请选择收款单位名称" />
                </a-form-model-item>
              </a-col> -->
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="2" header="费用信息">
            <a-row :gutter="48">
              <a-col :span="12">
                <a-form-model-item label="是否预付款" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isRelContract">
                  <j-dict-select-tag :disabled="formDisabled || model.itemList.length>0?true:false" type="radio" v-model="model.isRelContract" dictCode="yes_no" placeholder="请选择是否预付款" />
                </a-form-model-item>
              </a-col>
              <a-col :span="16">
                <div style="margin-bottom: 6px;margin-top: 6px">
                  <a-button @click="handleAdd" v-if="!formDisabled" type="primary" :disabled="model.itemList.length>0?true:false" >新增</a-button>
                </div>
              </a-col>
              <a-col :span="4">

              </a-col>
              <a-col :span="4">
                <div style="margin-top: 6px;float:right">
                  单位：元
                </div>
              </a-col>
              <a-col :span="24" v-show="model.isRelContract=='1'">
                <a-table
                  ref="table"
                  size="middle"
                  rowKey="id"
                  :components="draggableComponent"
                  :loading="loading"
                  bordered
                  :columns="model.isRelContract=='0'?noColumns:columns"
                  :pagination="false"
                  :data-source="model.itemList"
                  :scroll="{x:scrollX}"
                >
                  <span slot="projectId" slot-scope="text, record">
                    <a @click="goProjectDetail(record)">{{ loadProjectId(text) }}</a>
                  </span>
                  <span slot="relReimbursementBillId" slot-scope="text, record">
                    <a @click="goReimbursementDetail(record)">{{ loadReimbursement(text) }}</a>
                  </span>
                  <span slot="action" slot-scope="text, record">
                    <template v-if="!formDisabled && !showFlowSubmitButton">
                      <a-button
                        class="ruleButton"
                        :ghost="true"
                        type="primary"
                        icon="edit"
                        @click="handleEdit(record)"/>
                      <a-divider type="vertical"/>
                      <!-- <a-popconfirm title="确定复制行吗?" @confirm="() => handleCopy(record)">
                                  <a-button
                                      class="ruleButton"
                                      :ghost="true"
                                      type="primary"
                                      icon="copy"
                                  />
                              </a-popconfirm>
                              <a-divider type="vertical"/> -->
                      <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                        <a-button
                          class="ruleButton"
                          :ghost="true"
                          type="primary"
                          icon="delete"
                        />
                      </a-popconfirm>
                    </template>
                  </span>
                </a-table>
              </a-col>
              <a-col :span="24" v-show="model.isRelContract=='0'">
                <a-table
                  ref="table"
                  size="middle"
                  rowKey="id"
                  :components="draggableComponentOther"
                  :loading="loading"
                  bordered
                  :columns="noColumns"
                  :pagination="false"
                  :data-source="model.itemList"
                  :scroll="{x:scrollXOther}"
                >
                  <span slot="projectId" slot-scope="text, record">
                    <a @click="goProjectDetail(record)">{{ loadProjectId(text) }}</a>
                  </span>
                  <span slot="relReimbursementBillId" slot-scope="text, record">
                    <a @click="goReimbursementDetail(record)">{{ loadReimbursement(text) }}</a>
                  </span>
                  <span slot="action" slot-scope="text, record">
                    <template v-if="!formDisabled">
                      <a-button
                        class="ruleButton"
                        :ghost="true"
                        type="primary"
                        icon="edit"
                        @click="handleEdit(record)"/>
                      <a-divider type="vertical"/>
                      <!-- <a-popconfirm title="确定复制行吗?" @confirm="() => handleCopy(record)">
                          <a-button
                              class="ruleButton"
                              :ghost="true"
                              type="primary"
                              icon="copy"
                          />
                      </a-popconfirm>
                      <a-divider type="vertical"/> -->
                      <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                        <a-button
                          class="ruleButton"
                          :ghost="true"
                          type="primary"
                          icon="delete"
                        />
                      </a-popconfirm>
                    </template>
                  </span>
                </a-table>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="3" header="打款信息">
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item label="支付方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="payMode">
                  <j-dict-select-tag
                    :disabled="formDisabled || showFlowSubmitButton"
                    type="list"
                    v-model="model.payMode"
                    dictCode="payment_type"
                    placeholder="请选择支付方式"
                    @input="radioChange"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="收款方名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="payeeName">
                  <!--迭代10优化 付款申请单-关联往来单位中商户类型应为供应商和客户 -->
                  <SelectSupplierInput
                    :disabled="formDisabled || showFlowSubmitButton"
                    commercialType="2"
                    :isFinance="true"
                    v-model="model.payeeName"
                    @back="selectCustomer"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8" v-if="model.payMode=='1'|| model.payMode=='2'">
                <a-form-model-item label="收款方开户行" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="payeeBankName">
                  <a-input :disabled="formDisabled || showFlowSubmitButton" v-model="model.payeeBankName" placeholder="请输入收款方开户行" disabled></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8" v-if="model.payMode=='1'|| model.payMode=='2'">
                <a-form-model-item label="收款方账户" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="payeeAccountNo">
                  <a-input :disabled="formDisabled || showFlowSubmitButton" v-model="model.payeeAccountNo" :max-length="32" placeholder="请输入收款方账户" disabled></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8" v-if="model.payMode=='1'|| model.payMode=='2'">
                <a-form-model-item label="开户行联行号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="cnapsCode">
                  <a-input v-model="model.cnapsCode" placeholder="请输入开户行联行号" disabled></a-input>
                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="8" v-if="model.payMode=='1'|| model.payMode=='2'">
                <a-form-model-item label="联系人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="payeeContacts">
                  <a-input :disabled=formDisabled v-model="model.payeeContacts" placeholder="请输入收款联系人"  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8" v-if="model.payMode=='1'|| model.payMode=='2'">
                <a-form-model-item label="联系方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="payeeContactInfo">
                  <a-input :disabled=formDisabled v-model="model.payeeContactInfo" placeholder="请输入收款联系方式" type="number" ></a-input>
                </a-form-model-item>
              </a-col> -->
              <a-col :span="24">
                <a-form-model-item label="打款附言" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="postscript">
                  <a-textarea :disabled="formDisabled && !showFlowSubmitButton" v-model="model.postscript" rows="4" placeholder="请输入打款附言" :max-length="200"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="情况说明" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="payRemark">
                  <a-textarea :disabled="formDisabled || showFlowSubmitButton" v-model="model.payRemark" rows="4" placeholder="请输入情况说明" :max-length="500"/>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>

          <a-collapse-panel key="4" header="附件信息">
            <a-row :gutter="48">
              <a-col :span="24">
                <a-form-model-item label="附件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attachments">
                  <j-upload :disabled="formDisabled || showFlowSubmitButton" v-model="model.attachments"></j-upload>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
      <!-- <common-flow-list v-if="formBpm && model.bpmStatus !== '1'" :formData="formData" style="margin-top: 10px"></common-flow-list> -->
      <erp-finance-payment-slip-fee-detail-modal ref="itemList" @ok="modalFormOk" :applicant="model.applicant" :teamId="model.teamId"></erp-finance-payment-slip-fee-detail-modal>
      <ErpFinanceReimbursementPenetrate ref="reimbursementPenetrate"></ErpFinanceReimbursementPenetrate>
      <!-- 项目详情开始 -->
      <erp-project-report-modal ref="projectReport"></erp-project-report-modal>
      <!-- 项目详情结束 -->
    </j-form-container>
    <a-row type="flex" justify="center">
      <a-col :span="24">
        <!-- 流程历史跟踪 -->
        <common-flow-list v-if="formBpm && model.bpmStatus !== '1'" :formData="formData"></common-flow-list>
      </a-col>
      <a-col :span="24" style="text-align: center;margin-top: 15px">
        <a-button type="primary" v-if="formBpm" :style="{ marginRight: showFlowSubmitButton?'10px':'0px' }" @click="onPrint">打印</a-button>
        <a-button @click="submitForm('submit')" v-if="showFlowSubmitButton">提 交</a-button>
      </a-col>
    </a-row>
    <ErpFinancePaymentSlipFormPrint v-if="formBpm" class="print_style" id="paymentslipContent" :formData="model" :formDataHistory="formData"></ErpFinancePaymentSlipFormPrint>
  </a-spin>
</template>

<script>

import { getAction, httpAction } from '@/api/manage'
import moment from 'moment'
import { mapGetters } from 'vuex'
import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
import SelectSupplierInput from '@/views/scy/components/selectSupplier/SelectSupplierInput.vue'
import SelectProjectInput from '@/views/scy/components/SelectProjectInput'
import SelectCompanyFilesInput from '@/views/scy/components/SelectCompanyFilesInput'
import { filterMultiDictText, initDictOptions } from '@/components/dict/JDictSelectUtil'
import ErpFinancePaymentSlipFeeDetailModal from './ErpFinancePaymentSlipFeeDetailModal'
import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput'
import ErpFinanceReimbursementPenetrate from '@/views/scy/penetrate/ErpFinanceReimbursementPenetrate'
import CommonFlowList from '@/views/components/CommonFlowList.vue';
import Print from '@/utils/print/printarea.js';
import ErpFinancePaymentSlipFormPrint from './ErpFinancePaymentSlipFormPrint' // 打印
import { DragResizable } from '@/mixins/DragResizable'

export default {
    name: 'ErpFinancePaymentSlipForm',
    components: {
      SelectUserByDep,
      SelectTeamInput,
      SelectCompanyInput,
      SelectSupplierInput,
      SelectProjectInput,
      SelectCompanyFilesInput,
      ErpFinancePaymentSlipFeeDetailModal,
      ErpFinanceReimbursementPenetrate,
      CommonFlowList,
      ErpFinancePaymentSlipFormPrint,
      ErpProjectReportModal: () => import('@/views/erp/report/project/modules/ErpProjectReportModal')
    },
    mixins: [DragResizable],
    props: {
      // 流程表单data
    formData: {
      type: Object,
      default: () => {},
      required: false
    },
    // 表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    watch: {
      activeKey(key) {
        this.$forceUpdate()
      }
    },
    data () {
      return {
        model: {
          payMode: '1',
          isRelContract: '1',
          itemList: []
        },
        proposerDeptId:'',
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 }
        },
        activeKey: ['1', '2', '3', '4'],
        confirmLoading: false,
        validatorRules: {
          bpmBizTitle: [
              { required: true, message: '请输入流程标题!' }
          ],
          applicant: [
              { required: true, message: '请输入申请公司!' }
          ],
          teamId: [
              { required: true, message: '请选择费用所属团队!' }
          ],
          billCategory: [
              { required: true, message: '请选择单据类型!' }
          ],
        createTime: [
            { required: true, message: '请输入创建日期!' }
        ],
        handlerId: [
            { required: true, message: '请输入经办人编号!' }
        ],
        handlerDeptId: [
            { required: true, message: '请输入经办人部门ID!' }
        ],
        billNo: [
            { required: true, message: '请输入单据编号!' }
        ],
        isRelContract: [
            { required: true, message: '请输入是否关联合同!' }
        ],
        payMode: [
            { required: true, message: '请输入支付方式!' }
        ],
        payeeName: [
            { required: true, message: '请选择收款方名称!' }
        ],
        payeeBankName: [
            { required: true, message: '请输入收款方开户行!' }
        ],
        payeeAccountNo: [
            { required: true, message: '请输入收款方账户!' }
             // { pattern: /^\d{10,25}$/, message: '请输入正确的银行账户!' },
        ],
        cnapsCode: [
            { required: true, message: '请输入开户行联行号!' }
        ],
        payeeContacts: [
            { required: true, message: '请输入收款联系人!' }
        ],
        payRemark: [
            { required: true, message: '请输入情况说明!' }
        ],
        payeeContactInfo: [
            { required: true, message: '请输入收款联系方式!' },
            { pattern: /^1(3\d|4[5-8]|5[0-35-9]|6[567]|7[01345-8]|8\d|9[025-9])\d{8}$/, message: '请输入正确的联系方式!' }
        ]
        },
        url: {
          queryProjectReportById: '/api/erp/project/report/erpProjectReport/queryById',
          queryPaymentSlipFeeDetailById: '/api/erp/finance/payment/erpFinancePaymentSlipFeeDetail/queryByBillId',
          queryPurchaseSupplierById: '/api/erp/purchase/supplier/erpPurchaseSupplier/queryById',
          queryRelReimbursementBillId: '/api/erp/finance/reimbursement/erpFinanceReimbursementBill/queryById',
          queryPurchaseContractById: '/api/erp/purchase/contract/erpPurchaseContract/queryById',
          queryProjectContractById: '/api/erp/omc/contractmanager/erpOmcContractManagerEntrustFinal/listAll',
          getBillNo: '/api/erp/finance/payment/erpFinancePaymentSlip/getBillNo',
          add: '/api/erp/finance/payment/erpFinancePaymentSlip/add',
          edit: '/api/erp/finance/payment/erpFinancePaymentSlip/edit',
          queryById: '/api/erp/finance/payment/erpFinancePaymentSlip/queryById'
        },
        loading: false,
        dictOptions: {},
        columns: [
          {
            title: '序号',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },

          {
            title: '项目名称',
            align: 'center',
            dataIndex: 'projectId',
            width: 242,
            ellipsis: true,
            scopedSlots: { customRender: 'projectId' }
          },
          {
            title: '项目编号',
            align: 'center',
            width: 242,
            dataIndex: 'projectCode',
            ellipsis: true
          },
          // <!--迭代10财务优化 TASK#3400 付款申请单-子表删除“情况说明”，“项目承接人””-->
          // {
          //   title:'项目承接人',
          //   align:"center",
          //   dataIndex: 'projectUndertaker',
          //   customRender: (text,r) => {
          //     if (!text) {
          //       return ''
          //     } else {
          //       return filterMultiDictText(this.dictOptions['projectUndertaker'], text + '')
          //     }
          //   }
          // },
          {
            title:'业绩归属年度',
            align:"center",
            dataIndex: 'projectYear',
            width: 160,
          },
          // {
          //   title:'费用所属年度',
          //   align:"center",
          //   dataIndex: 'teamYear',
          //   customRender: (text,r) => {
          //     if (!text) {
          //       return ''
          //     } else {
          //       return filterMultiDictText(this.dictOptions['teamYear'], text + '')
          //     }
          //   }
          // },
          // {
          //   title:'费用所属团队',
          //   align:"center",
          //   dataIndex: 'teamId',
          //   customRender: (text) => {
          //     if (!text) {
          //       return ''
          //     } else {
          //       return filterMultiDictText(this.dictOptions['teamId'], text + '')
          //     }
          //   }
          // },
          {
            title: '合同类型',
            align: 'center',
            dataIndex: 'contractType',
            width: 242,
            ellipsis: true,
            customRender: (text) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['contractType'], text + '')
              }
            }
          },
          {
            title: '合同名称',
            align: 'center',
            dataIndex: 'contractId',
            width: 242,
            ellipsis: true,
            customRender: (text, record) => {
              if (!text) {
                return ''
              } else {
                if (record.contractType == '1') {
                  return filterMultiDictText(this.dictOptions['projectContractId'], text + '')
                } else {
                  return filterMultiDictText(this.dictOptions['contractId'], text + '')
                }
              }
            }
          },
          // {
          //   title:'费用类别',
          //   align:"center",
          //   dataIndex: 'projectFeeType',
          //   customRender: (text) => {
          //     if (!text) {
          //       return ''
          //     } else {
          //       return filterMultiDictText(this.dictOptions['projectFeeType'], text + '')
          //     }
          //   }
          // },
          // <!--迭代10财务优化 TASK#3400 付款申请单-子表删除“情况说明”，“项目承接人””-->
          // {
          //   title:'情况说明',
          //   align:"center",
          //   dataIndex: 'remark',
          // },
          // {
          //   title:'应付',
          //   align:"center",
          //   dataIndex: 'payableAmount',
          // },
          // {
          //   title:'已付',
          //   align:"center",
          //   dataIndex: 'paidAmount',
          // },
          // {
          //   title:'扣款',
          //   align:"center",
          //   dataIndex: 'deductionAmount',
          // },
          // {
          //   title:'本次扣款',
          //   align:"center",
          //   dataIndex: 'currentDeductionAmount',
          // },
          {
            title: '本次预付金额（元）',
            align: 'center',
            dataIndex: 'currentPaidAmount',
            width: 242,
            ellipsis: true
          },
          // {
          //   title:'未付款',
          //   align:"center",
          //   dataIndex: 'unpaidAmount',
          // },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            fixed: 'right',
            width: 160,
            scopedSlots: {
              filterDropdown: 'filterDropdown',
              filterIcon: 'filterIcon',
              customRender: 'action'
            }
          }
        ],
        // 非关联合同数据
        noColumns: [
          {
            title: '序号',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '费用报销单',
            align: 'center',
            dataIndex: 'relReimbursementBillId',
            scopedSlots: { customRender: 'relReimbursementBillId' },
            width: 242,
            ellipsis: true
          },
          // {
          //   title:'费用类别',
          //   align:"center",
          //   dataIndex: 'reimbursementFeeType'
          // },
          // {
          //   title:'所属团队',
          //   align:"center",
          //   dataIndex: 'teamId',
          //   customRender: (text) => {
          //     if (!text) {
          //       return ''
          //     } else {
          //       return filterMultiDictText(this.dictOptions['teamId'], text + '')
          //     }
          //   }
          // },
          {
            title: '应付（元）',
            align: 'center',
            dataIndex: 'payableAmount',
            width: 120,
            ellipsis: true
          },
          {
            title: '已付（元）',
            align: 'center',
            dataIndex: 'paidAmount',
            width: 120,
            ellipsis: true
          },
          {
            title: '扣款（元）',
            align: 'center',
            dataIndex: 'deductionAmount',
            width: 120,
            ellipsis: true
          },
          {
            title: '本次扣款（元）',
            align: 'center',
            dataIndex: 'currentDeductionAmount',
            width: 120,
            ellipsis: true
          },
          {
            title: '本次支付（元）',
            align: 'center',
            dataIndex: 'currentPaidAmount',
            width: 120,
            ellipsis: true
          },
          {
            title: '未付款（元）',
            align: 'center',
            dataIndex: 'unpaidAmount',
            width: 120,
            ellipsis: true
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            fixed: 'right',
            width: 160,
            scopedSlots: {
              filterDropdown: 'filterDropdown',
              filterIcon: 'filterIcon',
              customRender: 'action'
            }
          }
        ]
      }
    },
    computed: {
      formDisabled() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return true
          }
        }
        return false
      }
    },
    created () {
       // 备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      console.log(this.modelDefault,'craeted');
      
      // 如果是流程中表单，则需要加载流程表单data
      this.showFlowData()
      // 加载数据字典信息
      this.initDictConfig();
      if (this.formDisabled) {
        this.columns.pop()
        this.noColumns.pop()
      }
      this.customKey = 'columns'
      this.otherKey = 'noColumns'
    },
    methods: {
      loadProjectId(text) {
        if (!text) {
          return ''
        } else {
          return filterMultiDictText(this.dictOptions['projectId'], text + '')
        }
      },
      goProjectDetail(record) {
        const that = this
        this.$nextTick(() => {
          getAction(this.url.queryProjectReportById, { id: record.projectId }).then((res) => {
            if (res.success) {
              const model = res.result
              that.$refs.projectReport.getDetail(model);
              that.$refs.projectReport.title = '项目一览表';
            }
          })
        })
      },
      loadReimbursement(text) {
        if (!text) {
          return ''
        } else {
          return filterMultiDictText(this.dictOptions['relReimbursementBillId'], text + '')
        }
      },
      // 切换团队
      selectTeam(data) {
        this.model.teamYear = data[0].tdnd;
        if (data) {
          if (this.model.itemList) {
            this.$set(this.model, 'itemList', []);
            this.$set(this.model, 'payAmount', 0);
            this.$set(this.model, 'payeeBankName', null);
            this.$set(this.model, 'payeeAccountNo', null);
            this.$set(this.model, 'cnapsCode', null);
            this.$set(this.model, 'payeeName', null);
          }
        }
      },
      // 切换方式
      radioChange(data) {
        if (data) {
          // this.$set(this.model, 'payeeName', null);
          // this.$set(this.model, 'payeeBankName', null);
          // this.$set(this.model, 'payeeAccountNo', null);
          // this.$set(this.model, 'cnapsCode', null);
          // this.$set(this.model, 'payeeContacts', '');
          // this.$set(this.model, 'payeeContactInfo', '');
        }
      },
      // 选择单位
      selectCustomer(data) {
        if (data) {
          // this.$set(this.model, 'payeeName', null);
          this.$set(this.model, 'payeeBankName', data[0].bankName);
          this.$set(this.model, 'payeeAccountNo', data[0].bankAccountNo);
          this.$set(this.model, 'cnapsCode', data[0].cnapsCode);
        }
      },
      goReimbursementDetail(record) {
        this.$refs.reimbursementPenetrate.initData(record.relReimbursementBillId);
        this.$refs.reimbursementPenetrate.visible = true;
      },
      // 获取编号
      getBillNo() {
        getAction(this.url.getBillNo, {}).then((res) => {
          if (res.success) {
            let data = res.result.records || res.result
            this.$set(this.model, 'billNo', data);
            this.$set(this.model, 'bpmBizTitle', this.userInfo().employee.name + '-' + data);
          }
        })
      },
      // 加载数据字典信息
      initDictConfig() {
        initDictOptions('erp_finance_reimbursement_bill,bill_no,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'relReimbursementBillId', res.result)
          }
        })
        initDictOptions('erp_omc_team_manager,alias_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'teamId', res.result)
          }
        })
        initDictOptions('contract_type').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'contractType', res.result)
          }
        })
        initDictOptions('payment_expense_category').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'projectFeeType', res.result)
          }
        })
        initDictOptions('erp_omc_project,project_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'projectId', res.result)
          }
        })
        initDictOptions('erp_omc_contract_manager_final,htmc,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'projectContractId', res.result)
          }
        })
        initDictOptions('erp_purchase_contract,purchase_bill,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'contractId', res.result)
          }
        })
        initDictOptions('erp_employee_file,name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'projectUndertaker', res.result)
          }
        })
      },
      // 子表新增
      handleAdd() {
        // 是否关联合同的标识
        let flag = this.model.isRelContract == '1';
        this.$refs.itemList.add(flag);
        this.$refs.itemList.title = '新增';
        this.$refs.itemList.disableSubmit = false;
      },
      // 子表编辑
      handleEdit(record) {
        // 是否关联合同的标识
        let flag = this.model.isRelContract == '1';
        this.$refs.itemList.edit(record, flag);
        this.$refs.itemList.title = '修改';
        this.$refs.itemList.disableSubmit = false;
      },
      // 切换公司
      selectApplicant(data) {
        if (data) {
          if (this.model.itemList) {
            this.$set(this.model, 'itemList', []);
            this.$set(this.model, 'payAmount', 0);
            this.$set(this.model, 'payeeBankName', null);
            this.$set(this.model, 'payeeAccountNo', null);
            this.$set(this.model, 'cnapsCode', null);
            this.$set(this.model, 'payeeName', null);
          }
        }
      },
      // 子表复制行
      // handleCopy(record) {
      //   let itemList=this.model.itemList;
      //   record.id=  parseInt(Math.random() * 1000000000000);
      //   itemList.push(record);
      //   this.model.itemList=itemList;
      // },
      // 子表删除
      handleDelete(id) {
        for (let i = 0; i < this.model.itemList.length; i++) {
          if (this.model.itemList[i].id == id) {
            this.model.itemList.splice(i, 1);
          }
        }
        let payAmount = 0;
        this.model.itemList.forEach(item => {
          payAmount += item.currentPaidAmount.toFixed(2);
        });
        this.$set(this.model, 'payAmount', payAmount);
      },
      modalFormOk(data) {
        this.loading = true;
        let flag = true;
        // debugger;
        for (let i = 0; i < this.model.itemList.length; i++) {
          if (this.model.itemList[i].id == data.id) {
            this.model.itemList.splice(i, 1, data);
            flag = false;
          }
        }
        if (flag) {
          this.model.itemList.push(data);
        }
        // 支付金额
        let payAmount = 0;
        this.model.itemList.forEach(item => {
          payAmount += item.currentPaidAmount.toFixed(2)
        });
        this.$set(this.model, 'payAmount', payAmount);
        // 判断合同或费用报销单的信息
        if (this.model.itemList.length > 0) {
          let obj = this.model.itemList[0];
          // 项目合同
          if (obj.contractType == '1') {
            if (obj.contractId) {
              // 获取对应的受托方信息
              getAction(this.url.queryProjectContractById, { mainId: obj.contractId, isSk: '1' }).then((res) => {
                if (res.success) {
                  let result = res.result;
                  if (result) {
                    this.$set(this.model, 'payeeName', result[0].khdaId);
                    if (result[0].khdaId) {
                      getAction(this.url.queryPurchaseSupplierById, { id: result[0].khdaId }).then((res) => {
                        if (res.success) {
                          let result = res.result;
                          if (result) {
                            this.$set(this.model, 'payeeBankName', result.bankName);
                            this.$set(this.model, 'payeeAccountNo', result.bankAccountNo);
                            this.$set(this.model, 'cnapsCode', result.cnapsCode);
                          }
                      }
});
                    }
                  }
                }
              })
            } else {
              this.$set(this.model, 'payeeName', null);
              this.$set(this.model, 'payeeBankName', '');
              this.$set(this.model, 'payeeAccountNo', '');
              this.$set(this.model, 'cnapsCode', '');
            }
          } else if (obj.contractType == '2') {
            if (obj.contractId) {
              getAction(this.url.queryPurchaseContractById, { id: obj.contractId }).then((res) => {
                if (res.success) {
                  let result = res.result;
                  if (result) {
                    this.$set(this.model, 'payeeName', result.supplyCompanName);
                    if (result.supplyCompanName) {
                      getAction(this.url.queryPurchaseSupplierById, { id: result.supplyCompanName }).then((res) => {
                      if (res.success) {
                        let result = res.result;
                        if (result) {
                          this.$set(this.model, 'payeeBankName', result.bankName);
                          this.$set(this.model, 'payeeAccountNo', result.bankAccountNo);
                          this.$set(this.model, 'cnapsCode', result.cnapsCode);
                        }
                    }
});
                    }
                  }
                }
              })
            } else {
              this.$set(this.model, 'payeeName', null);
              this.$set(this.model, 'payeeBankName', '');
              this.$set(this.model, 'payeeAccountNo', '');
              this.$set(this.model, 'cnapsCode', '');
            }
          } else {
              this.$set(this.model, 'payeeName', null);
              this.$set(this.model, 'payeeBankName', '');
              this.$set(this.model, 'payeeAccountNo', '');
              this.$set(this.model, 'cnapsCode', '');
            }
          // 是否关联费用报销单
          if (obj.relReimbursementBillId) {
            getAction(this.url.queryRelReimbursementBillId, { id: obj.relReimbursementBillId }).then((res) => {
              if (res.success) {
                let result = res.result;
                if (result) {
                  // 供应商
                  if (result.transferType == '2') {
                    this.$set(this.model, 'payeeName', result.accountName);
                    this.$set(this.model, 'payeeBankName', result.bankName);
                    this.$set(this.model, 'payeeAccountNo', result.accountNo);
                    this.$set(this.model, 'cnapsCode', result.cnapsCode);
                  }
                }
              }
            })
          }
        }
        this.loading = false;
      },
      ...mapGetters(['userInfo']),
      add () {
        this.edit(this.modelDefault);
        console.log(this.modelDefault,'modelDefault');
        this.$set(this.model, 'itemList', []);
        this.getBillNo();
        this.model.proposer = this.userInfo().empId;
        this.model.proposerDeptId = this.userInfo().deptId;
        // this.model.applicant = this.userInfo().employee.orgDepart; //当前登录人单位
        this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
        console.log(this.model.proposerDeptId,'添加');
        
      },
      edit (record) {
        this.$refs.form.resetFields();
        this.model = Object.assign({}, record);
        console.log(record,'record');
        console.log(this.model,'model');
        console.log(this.model.proposerDeptId,'this.model.proposerDeptId');
        console.log(this.model.bpmBizTitle,'this.model.bpmBizTitle');
        console.log(this.model.id,'this.model.bpmBizTitle');
        
         this.proposerDeptId = this.model.proposerDeptId;
        // 如果id存在
        if (this.model.id) {
          getAction(this.url.queryPaymentSlipFeeDetailById, { billId: this.model.id }).then((res) => {
            if (res.success) {
              let result = res.result;
              if (result) {
                this.$set(this.model, 'itemList', result);
              } else {
                this.$set(this.model, 'itemList', []);
              }
            } else {
              this.$set(this.model, 'itemList', []);
            }
          })
        }
        this.visible = true;
      },
      // 渲染流程表单数据
      showFlowData() {
        if (this.formBpm === true) {
          let params = { id: this.formData.dataId }
          getAction(this.url.queryById, params).then((res) => {
            if (res.success) {
              this.edit(res.result)
            }
          })
        }
      },

      submitForm(type) {
        const that = this;
        if (type == 'draft') {
          // 代表保存草稿不做校验
          this.submit(type)
        } else if (type == 'submit') {
          // 触发表单验证
          this.$refs.form.validate(valid => {
            if (valid) {
              if (this.model.itemList.length == 0) {
                that.$message.warning('请添加费用信息');
                that.confirmLoading = false;
                that.$emit('unButtonDisable');
                return;
              }
              that.submit(type)
            } else {
              that.$emit('unButtonDisable')
            }
          })
        } else {
          console.log('传参数，保存：draft，提交：submit')
        }
      },
      submit (type) {
        const that = this;
        let teamName = filterMultiDictText(this.dictOptions['teamId'], that.model.teamId + '')
        let createTime = this.getCreateTime()
        // 迭代16.7 取费用所属团队-申请人-申请日期（年月日）-金额（取本次支付）
        // fix bug 7407 【付款单】流程标题中金额前0多余 start
        let payAmount = this.processPayment()
        console.log('--payAmount', payAmount)
        // fix bug 7407 【付款单】流程标题中金额前0多余 end
        that.model.bpmBizTitle = (that.model.teamId ? teamName + ' - ' : '') + that.userInfo().empName + ' - ' + createTime + (this.model.payAmount ? ' - ' + payAmount : '')// 标题
        that.confirmLoading = true;
        let httpurl = '';
        let method = '';
        if (!this.model.id) {
          httpurl += this.url.add;
          method = 'post';
        } else {
          httpurl += this.url.edit;
          method = 'put';
        }
        httpAction(httpurl, this.model, method).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            if (method == 'post') {
              that.model.id = res.result;
            }
            that.$emit('ok', type, that.model);
          } else {
            that.$message.warning(res.message);
            that.$emit('unButtonDisable');
          }
        }).catch((error) => {
          that.$emit('unButtonDisable', error);
        }).finally(() => {
          that.confirmLoading = false;
        })
      },

      // 点击打印
      onPrint () {
        let print = new Print({
          el: '#paymentslipContent',
          popTitle: '付款申请详情 · 禾美环保',
          endCallback() {

          }
        })
      },
      getCreateTime() {
        let createTime = this.model.createTime;
        let date = createTime.substring(0, 10)
        return date.substring(0, 4) + '年' + date.substring(5, 7) + '月' + date.substring(8, 10) + '日';
      },
      processPayment() {
        let payment = this.model.payAmount + ''
        let firstChar = payment.substring(0, 1)
        if (firstChar === '0') {
          payment = payment.substring(1, payment.length)
        }
        return payment
      }
    }
  }
</script>
<style>
  @import "../../../../../utils/print.css";
  .print_style{
  position: absolute;
  top: 0;
  z-index: -1111;
}
</style>
